import axios from 'axios'
import md5 from "js-md5";
import { getToken } from '@/axios/auth'
import router from '@/router/index'
import { Message, MessageBox } from 'element-ui'

let baseURL = "";
if (process.env.NODE_ENV === "development") {
  baseURL = "/proxy";
} else {
  baseURL = "";
}
// 创建axios实例
const service = axios.create({
  baseURL: baseURL, // api 的 base_url
  timeout: 500000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    const index = config.url.indexOf('/api')
    const url = config.url.slice(index)
    let token = getToken() // 让每个请求携带自定义签名
    token.sign = md5(token.sign+url);
    config.headers = token;
      return config
    
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code !=200 && res.code != 407 && res.code != 405) {
      // Message({
      //   message: res.message,
      //   type: 'error',
      //   duration: 2000
      // })

      return Promise.reject(response.data);
    } 
    else 
    if(res.code === 407){
      console.log(router)
      router.replace({
        path:'/Login'
      })
      localStorage.userInfo = null;
      if(sessionStorage.getItem("token")){
         sessionStorage.clear();
        Message({
          message: `登录失效,请重新登录`,
          type: 'error',
          duration: 5 * 1000
        })
      }

    }else if(res.code === 405){
      Message({
        message: '您访问的太快啦！',
        type: 'error',
        duration: 5 * 1000
      })
    }
    else {
      return response.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: '操作失败',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
